import torch
import torchvision
import torch.utils.data
import os
import pandas
import xml.dom.minidom


class BananaDataset(torch.utils.data.Dataset):
    def __init__(self, root, image_dir, annotations_file, transform=None, target_transform=None):
        self.image_path = os.path.join(root, image_dir)
        self.transform = transform
        self.img_labels = pandas.read_csv(os.path.join(root, annotations_file))
        self.target_transform = target_transform

    def __len__(self):
        return len(self.img_labels)

    def __getitem__(self, idx):
        image = torchvision.io.read_image(os.path.join(self.image_path, self.img_labels.iloc[idx][0])).to(torch.float32)
        label = torch.tensor(self.img_labels.iloc[idx][1:], dtype=torch.float32)
        image_scale = torch.tensor([image.shape[2], image.shape[1], image.shape[2], image.shape[1]],
                                   dtype=torch.float32)
        label[1:] = label[1:] / image_scale
        if self.transform:
            image = self.transform(image)
        if self.target_transform:
            label = self.target_transform(label)
        return image, label
